package com.tutor.lzm.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.LogUtil;
import com.tutor.lzm.AppSession;
import com.tutor.lzm.R;
import com.tutor.lzm.activity.MainActivity;
import com.tutor.lzm.activity.TeacherDetailsAct;
import com.tutor.lzm.activity.WebViewAct;
import com.tutor.lzm.adapter.SingleCourseAdapter;
import com.tutor.lzm.adapter.TeacherAdapter;
import com.tutor.lzm.bean.CarouseFigureBean;
import com.tutor.lzm.bean.SubjectBean;
import com.tutor.lzm.bean.TeacherRecommendBean;
import com.tutor.lzm.entity.CarouseFigureEntity;
import com.tutor.lzm.entity.TeacherRecommendEntity;
import com.tutor.lzm.http.BaseResponse;
import com.tutor.lzm.http.HttpClient;
import com.tutor.lzm.http.request.CarouseFigureRequest;
import com.tutor.lzm.http.request.GetAllSubjectRequest;
import com.tutor.lzm.http.request.TeacherRecommendRequest;
import com.tutor.lzm.http.response.TeacherRecommendList;
import com.tutor.lzm.utils.ViewFactory;
import com.tutor.lzm.view.viewpager.CycleViewPager;
import com.tutor.syslib.Logs;
import com.tutor.syslib.listener.PullUpRefreshImpl;
import com.tutor.syslib.view.MyListView;
import com.tutor.syslib.view.MyScrollView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by zzgpc on 2017-8-24.
 * 首页
 */
public class MainFragment extends BaseFragment {
    private String tag = "MainFragment";


    @BindView(R.id.tv_select_city)
    TextView tvSelectCity;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.img_message)
    ImageView imgMessage;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.rl_college_students)
    RelativeLayout rlCollegeStudents;
    @BindView(R.id.rl_teacher_group)
    RelativeLayout rlTeacherGroup;
    @BindView(R.id.rl_summer_vacation_class)
    RelativeLayout rlSummerVacationClass;
    @BindView(R.id.rl_featured_courses)
    RelativeLayout rlFeaturedCourses;
    @BindView(R.id.rl_teacher_in_service)
    RelativeLayout rlTeacherInService;
    @BindView(R.id.ll_policy)
    LinearLayout llPolicy;
    @BindView(R.id.popular_recommendation_listView)
    MyListView popularRecommendationListView;
    @BindView(R.id.my_scroll_view)
    MyScrollView myScrollView;
    Unbinder unbinder;

    /**
     * 加载位置坐标
     */
    private int currentPage = 0;
    private CycleViewPager cycleViewPager;
    /**
     * 广告页面数据
     */
    public List<CarouseFigureBean> ADInfoList = new ArrayList<>();
    /**
     * 热门推荐老师adapter
     */
    private TeacherAdapter adapter;


    /**
     * 热门推荐老师
     */
    private List<TeacherRecommendBean> recommendBeanList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public int getFragmentLayout() {
        return R.layout.fragment_main;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        contentView = inflater.inflate(getFragmentLayout(), container, false);
        unbinder = ButterKnife.bind(this, contentView);
        super.onCreateView(inflater, container, savedInstanceState);
        return contentView;
    }

    @Override
    protected void initView(Bundle bundle) {
        super.initView(bundle);
        cycleViewPager = (CycleViewPager) getActivity().getFragmentManager()
                .findFragmentById(R.id.main_viewPager);
        initListView();
        imgMessage.setFocusable(true);
        imgMessage.setFocusableInTouchMode(true);
    }


    private void initListView() {
        MyListView myListView = (MyListView) findViewById(R.id.popular_recommendation_listView);
        adapter = new TeacherAdapter(getContext(), recommendBeanList);
        myListView.setAdapter(adapter);
        myScrollView.setPullUpRefreshImpl(pullUpRefresh);
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TeacherRecommendBean bean = recommendBeanList.get(position);
                String teacherId = bean.teacherId;
                TeacherDetailsAct.start(getContext(), teacherId);
            }
        });
    }

    @Override
    protected void initData(Bundle bundle) {
        super.initData(bundle);
        getAD();
        getRecommendSubject();
        getAllSubject();
    }

    @SuppressLint("NewApi")
    private void initialize(List<CarouseFigureBean> infos) {

        List<ImageView> views = new ArrayList<ImageView>();
        // 将最后一个ImageView添加进来
        views.add(ViewFactory.getImageView(getContext(), infos.get(infos.size() - 1).imgAddress));
        for (int i = 0; i < infos.size(); i++) {
            views.add(ViewFactory.getImageView(getContext(), infos.get(i).imgAddress));
        }
        // 将第一个ImageView添加进来
        views.add(ViewFactory.getImageView(getContext(), infos.get(0).imgAddress));

        // 设置循环，在调用setData方法前调用
        cycleViewPager.setCycle(true);

        // 在加载数据前设置是否循环
        cycleViewPager.setData(views, infos, mAdCycleViewListener);
        //设置轮播
        cycleViewPager.setWheel(true);

        // 设置轮播时间，默认5000ms
        cycleViewPager.setTime(2000);
        //设置圆点指示图标组居中显示，默认靠右
        cycleViewPager.setIndicatorCenter();
    }

    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(CarouseFigureBean info, int position, View imageView) {
            if (cycleViewPager.isCycle()) {
                position = position - 1;
                WebViewAct.start(getContext(), ADInfoList.get(position).eventUrl);
            }

        }

    };


    /**
     * 初始化学科
     */
    private void initSubject(List<SubjectBean> subjectList) {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        SingleCourseAdapter singleCourseAdapter = new SingleCourseAdapter(getContext(), subjectList);
        recyclerView.setAdapter(singleCourseAdapter);

    }


    /**
     * 获取轮播广告业信息
     */
    private void getAD() {
        final CarouseFigureRequest request = new CarouseFigureRequest();
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                Logs.e("mainfragment", response.toString());
                ADInfoList = (List<CarouseFigureBean>) response;
//                    ADInfoList = carouseFigureEntity.body;
                initialize(ADInfoList);

            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
            }
        });

    }

    /**
     * 获取所有学科
     */
    private void getAllSubject() {
        GetAllSubjectRequest request = new GetAllSubjectRequest();
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {

                try {
                    List<SubjectBean> subjectList = (List<SubjectBean>) response;
                    AppSession.getInstance().setSubjectList(subjectList);
                    initSubject(subjectList);
                    Logs.e(tag, "subjectList大小为 " + subjectList.size());
                } catch (Exception e) {
                    Logs.e(tag, "onSuccess   getAllSubject接口错误， e=" + e);
                }

            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                Logs.e(tag, "onFailListener    getAllSubject接口错误， msg=" + msg);
            }
        });
    }

    /**
     * 获取热门推荐老师
     */
    private void getRecommendSubject() {
        final TeacherRecommendRequest request = new TeacherRecommendRequest();
        request.start = currentPage;
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {

                Logs.e("mainfragment", "response");
                TeacherRecommendList recommendList = (TeacherRecommendList) response;
                List<TeacherRecommendBean> adResponse = recommendList.teacherRecommendList;
                recommendBeanList.addAll(adResponse);
                adapter.notifyDataSetChanged();
                if (adResponse.size() != 0) {
                    currentPage++;
                }
                return;

            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                Logs.d("MainFragment", "getRecommendSubject    code" + code + "      msg=" + msg);
            }
        });

    }


    /**
     * MyScrollView下拉刷新
     */
    private PullUpRefreshImpl pullUpRefresh = new PullUpRefreshImpl() {
        @Override
        public void setOnPullUpRefresh() {
            int size = recommendBeanList.size();
            if (size % 10 == 0) {
                getRecommendSubject();
            }

        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
